package com.qfedu.aunt.commons.auth.security;


import com.qfedu.aunt.commons.result.R;
import com.qfedu.aunt.commons.utils.ResponseUtils;
import com.qfedu.aunt.commons.utils.UserInfoContainer;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出的处理器
 * 原本的Security退出登陆的时候是需要跳转到一个页面的
 * 但是前后分离的项目中 退出之后 只能返回JSON格式的字符串告诉他是成功还是失败
 */
public class TokenLogoutHandler implements LogoutHandler {
    private TokenManager tokenManager;

    public TokenLogoutHandler(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //1 从header里面获取token
        //2 token不为空，移除token，从redis删除token
        String token = request.getHeader("token");
        if(token != null) {
            //移除
            tokenManager.removeToken(token);
            //从token获取用户名
            //这里需要删除用户的权限信息
            UserInfoContainer.remove(token);
        }
        ResponseUtils.out(response, R.ok());
    }
}
